import React, { useEffect, useState } from 'react';
import dayjs from 'dayjs';
import {
  Modal,
  Upload,
  Button,
  List,
  Typography,
  message,
  Popconfirm,
  Space,
  Tag,
  Pagination
} from 'antd';
import {
  UploadOutlined,
  DeleteOutlined,
  DownloadOutlined,
  EyeOutlined,
  CheckCircleTwoTone
} from '@ant-design/icons';
import {
  getResumes,
  uploadResume,
  deleteResume,
  setDefaultResume
} from '../api/user';

const { Text } = Typography;

export default function ResumeModal({ open, onClose }) {
  const [resumes, setResumes] = useState([]);
  const [uploading, setUploading] = useState(false);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const pageSize = 5;
  const baseURL = 'http://localhost:8080';
  const [modalVisible, setModalVisible] = useState(false); // 控制提示弹窗的可见性

  const fetchResumes = async () => {
    const res = await getResumes(page, pageSize);
    if (res.success) {
      setResumes(res.data.records || []);
      setTotal(res.data.total || 0);
    } else {
      message.error(res.message || '获取简历失败');
    }
  };

  useEffect(() => {
    if (open) fetchResumes();
  }, [open, page]);

  const handleUpload = async ({ file, onSuccess, onError }) => {
    if (total >= 9) {
      // 显示 Ant Design 的提示弹窗
      setModalVisible(true);
      onError('最多只能上传9份简历');
      return;
    }

    setUploading(true);
    try {
      const res = await uploadResume(file);
      if (res.success) {
        message.success('上传成功');
        setPage(1); // 上传后返回第一页
        fetchResumes();
        onSuccess(res, file);
      } else {
        message.error(res.message || '上传失败');
        onError(res.message);
      }
    } catch (err) {
      message.error('上传出错');
      onError(err);
    } finally {
      setUploading(false);
    }
  };

  const handleDelete = async (id) => {
    const res = await deleteResume(id);
    if (res.success) {
      message.success('删除成功');
      fetchResumes();
    } else {
      message.error(res.message || '删除失败');
    }
  };

  const handleSetDefault = async (id) => {
    const res = await setDefaultResume(id);
    if (res.success) {
      message.success('已设为默认简历');
      fetchResumes();
    } else {
      message.error(res.message || '设置失败');
    }
  };

  const handleDownload = async (url, filename) => {
  try {
    const response = await fetch(url);
    const blob = await response.blob();
    const downloadUrl = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = downloadUrl;
    a.download = filename; // 设置下载的文件名
    document.body.appendChild(a);
    a.click();
    a.remove();
    window.URL.revokeObjectURL(downloadUrl);
  } catch (error) {
    message.error('下载失败');
  }
};

  return (
    <Modal
      open={open}
      onCancel={onClose}
      footer={null}
      title="我的简历"
      width={700}
    >
      {/* 自定义提示弹窗 */}
      <Modal
        title="提示"
        visible={modalVisible}
        onOk={() => setModalVisible(false)}
        onCancel={() => setModalVisible(false)}
        footer={[
          <Button key="ok" type="primary" onClick={() => setModalVisible(false)}>
            确定
          </Button>
        ]}
      >
        <p>最多只能上传9份简历</p>
      </Modal>

      <Upload
        accept=".pdf"
        customRequest={handleUpload}
        showUploadList={false}
        multiple
      >
        <Button
          type="primary"
          icon={<UploadOutlined />}
          loading={uploading}
          style={{ marginBottom: 16 }}
        >
          上传简历（PDF）
        </Button>
      </Upload>

      {/* 添加已上传简历数量的提示 */}
      <span style={{ marginLeft: 8, fontSize: 14, color: '#666' }}>
        已上传 {total} / 9 份简历
      </span>

      <List
        itemLayout="horizontal"
        dataSource={resumes}
        locale={{ emptyText: '暂无上传简历' }}
        renderItem={(item) => (
          <List.Item
            actions={[
              <a
                href={`${baseURL}${item.url}`}
                target="_blank"
                rel="noopener noreferrer"
                key="preview"
              >
                <EyeOutlined /> 预览
              </a>,
              <a
                href="#"
                onClick={(e) => {
                  e.preventDefault();
                  handleDownload(`${baseURL}${item.url}`, item.filename);
                }}
                key="download"
              >
                <DownloadOutlined /> 下载
              </a>,
              <Popconfirm
                title="确定删除这份简历？"
                onConfirm={() => handleDelete(item.id)}
                okText="确定"
                cancelText="取消"
                key="delete"
              >
                <Button type="link" icon={<DeleteOutlined />} danger>
                  删除
                </Button>
              </Popconfirm>,
              !item.default && (
                <Button
                  type="link"
                  onClick={() => handleSetDefault(item.id)}
                  key="default"
                >
                  设为默认
                </Button>
              )
            ]}
          >
            <List.Item.Meta
              title={
                <Space>
                  {item.filename}
                  {item.default && (
                    <Tag color="blue" icon={<CheckCircleTwoTone twoToneColor="#1890ff" />}>
                      默认简历
                    </Tag>
                  )}
                </Space>
              }
              description={
                <Text type="secondary">上传时间：{dayjs(item.uploaded_at).format('YYYY-MM-DD HH:mm:ss')}</Text>
              }
            />
          </List.Item>
        )}
      />

      {/* 分页器 */}
      {total > pageSize && (
        <Pagination
          current={page}
          total={total}
          pageSize={pageSize}
          style={{ textAlign: 'right', marginTop: 16 }}
          onChange={(p) => setPage(p)}
          showSizeChanger={false}
        />
      )}
    </Modal>
  );
}